package top.tomxwd.service.impl;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.tomxwd.service.PaymentService;

import java.util.concurrent.TimeUnit;

/**
 * @author xieweidu
 * @createDate 2020-08-02 18:17
 */
@Service
@Slf4j
public class PaymentServiceImpl implements PaymentService {

    /* ==========================服务降级========================== */
    @Override
    public String paymentInfoOk(Integer id) {
        return "ok------线程池：" + Thread.currentThread().getName() + "paymentInfoOk id=" + id;
    }

    @Override
    @HystrixCommand(fallbackMethod = "paymentInfoTimeoutFallBack", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    public String paymentInfoTimeout(Integer id) {
        try {
            log.info("paymentInfoTimeout当前线程：" + Thread.currentThread().getName());
//            int age = 10 / 0;
            TimeUnit.SECONDS.sleep(2);
//            TimeUnit.MILLISECONDS.sleep(500L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "timeout------线程池：" + Thread.currentThread().getName() + "paymentInfoTimeout id=" + id;
    }

    public String paymentInfoTimeoutFallBack(Integer id) {
        log.info("paymentInfoTimeoutFallBack当前线程：" + Thread.currentThread().getName());
        return Thread.currentThread().getName() + "调用超时 id = " + id;
    }

    /* ==========================服务熔断========================== */
    @HystrixCommand(fallbackMethod = "paymentCircuitBreakerFallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),
    })
    @Override
    public String paymentCircuitBreaker(Integer id) {
        if (id < 0) {
            throw new RuntimeException("id 不能为负数");
        }
        String serialNumber = IdUtil.simpleUUID();
        log.info("打印交易流水号：{}", serialNumber);
        return Thread.currentThread().getName() + "\t调用成功，流水号为：" + serialNumber;
    }

    public String paymentCircuitBreakerFallback(Integer id) {
        return "id不能为负数，请稍后再试 id = " + id;
    }

}
